package com.managertrade.config;

import com.managertrade.annotation.RequiresPermissions;
import com.managertrade.common.ErrorCode;
import com.managertrade.common.ServiceException;
import com.managertrade.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            throw new ServiceException(ErrorCode.USER_NOT_LOGIN);
        }
        token = token.replace("Bearer ", "");
        //校验token是否过期
        boolean tokenExpired = JwtUtil.isTokenExpired(token);
        if(tokenExpired){
            throw new ServiceException(ErrorCode.UNAUTHORIZED);
        }
        Claims claims = JwtUtil.parseToken(token);
        Long userId = claims.get("userId", Long.class);
        List<String> userPerms = (List<String>) claims.get("perms");

        // 保存用户信息到请求作用域中（可选）
        request.setAttribute("userId", userId);
        request.setAttribute("userPerms", userPerms);
        if (handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod) handler;
            Method method = hm.getMethod();
            RequiresPermissions rp = method.getAnnotation(RequiresPermissions.class);
            if (rp != null) {
                for (String need : rp.value()) {
                    if (userPerms.contains(need)) return true;
                }
                throw new ServiceException(ErrorCode.FORBIDDEN);
            }
        }
        return true;
    }
}
